package programmercarl.回溯.C7;

import java.util.ArrayList;
import java.util.List;

class Solution {

    List<List<Integer>> ans = new ArrayList<>();

    List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtrack(candidates,target,0,0);
        return ans;
    }

    private void backtrack(int[] candidates, int target, int start,int sum) {
        if (sum > target) {
            return;
        }
        if(sum == target) {
            ans.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            list.add(candidates[i]);
            sum += candidates[i];
            //全是正数，若>target,则break
            if(sum > target) {break;}
            backtrack(candidates, target, i, sum);
            list.remove(list.size() - 1);
            sum -= candidates[i];
        }
    }

}